let express = require('express');

let router = express.Router()

let db = require("./db")

let bodyParser = require("body-parser")

let urlPar = bodyParser.urlencoded({ extended: true })

router.get("/getlist", async function (req, res) {
    let { seach, order = 'id', sort = 'asc', pageSize = 5, currentPage = 0 } = req.query
    let sql = `select * from classify`
    let num = pageSize * currentPage
    if (seach) {
        sql += `   where name like '%${seach}%'`
    }
    sql += `   order by ${order} ${sort}`
    if (num) {
        sql += `  limit ${num},${pageSize}`
    } else {
        sql += `  limit ${currentPage},${pageSize}`
    }
    let r = await db.doMysql(sql)
    console.log(r)
    res.send(db.backText(r))
})

router.post('/postlist', urlPar, async function (req, res) {
    let { name } = req.body
    let sql = `insert into classify (name) values ('${name}')`
    let r = await db.doMysql(sql)
    res.send(db.postText(r))
})

router.post("/update", urlPar, async function (req, res) {
    let { name, id } = req.body
    let sql = `update classify set name='${name}' where id='${id}'`
    let r = await db.doMysql(sql)
    res.send(db.postText(r))
})

router.get("/delete", async function (req, res) {
    let { id } = req.query
    let sql = `delete from classify where id in (${id})`
    let r = await db.doMysql(sql)
    res.send(db.delText(r))
})

module.exports = router